<template>
  <div>
    <!-- 顶部操作区域 -->
    <div class="top">
      <!-- 若需要搜索，可添加搜索框 -->
      <el-input
        v-model="kwInput"
        style="width: 400px"
        placeholder="请输入关键字筛选"
        class="input-with-select"
        clearable
        @keyup.native.enter="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </el-input>
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create')"
      >
        添加代理
      </el-button>

      <el-button
        type="danger"
        :disabled="!multipleSelection.length"
        @click="handleAction('deleteBatch')"
      >
        删除选中
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="data"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <!-- 多选列 -->
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <!-- 若你的后端有id，可直接显示id -->
      <el-table-column
        prop="id"
        label="ID"
        width="80"
      />
      <el-table-column
        prop="create_at"
        label="创建日期"
      />

      <!-- 代理（host:port） -->
      <el-table-column
        label="代理"
        width="240"
      >
        <template slot-scope="scope">
          <!-- 显示拼接好的代理信息 -->
          <span>{{ scope.row.host }}:{{ scope.row.port }}</span>
        </template>
      </el-table-column>

      <!-- 是否可用的switch -->
      <el-table-column
        label="是否可用"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDead"
            active-color="#ff4949"
            inactive-color="#13ce66"
            active-text="不可用"
            inactive-text="可用"
            @change="handleUpdateStatus(scope.row)"
          />
        </template>
      </el-table-column>

      <!-- 类型 -->
      <el-table-column
        prop="type"
        label="类型"
        width="120"
      />

      <!-- 来源 -->
      <el-table-column
        prop="source"
        label="来源"
        width="120"
      />

      <!-- 其他信息 -->
      <el-table-column
        prop="tag"
        label="其他信息"
        min-width="180"
      />

      <!-- 操作列 -->
      <el-table-column
        label="操作"
        width="180"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="handleAction('edit', scope.row)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleAction('delete', scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（可按需添加，如果后端支持分页）-->
    <el-pagination
      v-if="data.length"
      background
      :current-page="page"
      :page-sizes="[10,20,50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      class="mt-pagination"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
    />

    <el-dialog
      :title="dialogTitle"
      :visible.sync="innerDialogVisible"
      :width="dialogWidth"
      :close-on-click-modal="false"
    >
      <el-form
        v-if="action !== 'delete'"
        :model="temp"
        label-position="left"
        label-width="80px"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="类型">
              <el-select v-model="temp.type" placeholder="选择类型">
                <el-option label="http" value="http" />
                <el-option label="socks5" value="socks5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源">
              <el-select v-model="temp.source" placeholder="来源">
                <el-option label="购买" value="buy" />
                <el-option label="爬取" value="crawl" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="proxies">
          <el-input
            v-model="temp.proxies"
            type="textarea"
            :rows="5"
            :placeholder="proxies_placeholder"
          />
        </el-form-item>

        <el-form-item label="其他信息">
          <el-input
            v-model="temp.tag"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>

      <!-- 若为删除，直接提示 -->
      <div v-else style="padding: 20px;font-size: 14px;line-height: 1.5;">
        确认要删除代理
        <span style="color: #c55;">{{ temp.host }}:{{ temp.port }}</span>
        吗？
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button
          :type="action !== 'delete' ? 'primary' : 'danger'"
          @click="confirm"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/eco/proxy'
// 假设你的后端有四个方法分别对应 CRUD，
// 如果后端没有 Add 而是用 Post 来创建，记得在 confirm 里用 Post() 即可
export default {
  name: 'ProxyManager',
  data() {
    return {
      data: [], // 表格数据
      listLoading: false, // 加载中
      // 分页相关
      page: 1,
      pagesize: 10,
      total: 0,
      // 搜索
      kwInput: '',
      // 弹窗相关
      innerDialogVisible: false,
      dialogTitle: '',
      dialogWidth: '30%',
      action: null,
      // 当前弹窗编辑/新增/删除的数据
      temp: {
        type: 'http',
        proxies: '',
        source: 'buy',
        tag: ''
        // 也可在这里加上 host, port 等
      },
      proxies_placeholder: 'HTTP代理格式: ip:port:username:password',
      // 多选
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true
      Get()
        .then((res) => {
          // 假设后端返回的数据结构为 { data: { proxies: [...], total: xxx } }
          this.data = res.data.data || []
          this.total = res.data.total || 0
          this.listLoading = false
        })
        .catch((err) => {
          console.log(err)
          this.listLoading = false
        })
    },
    // 点 “添加”、“修改”、“删除”、“批量删除” 按钮
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.dialogTitle = '添加代理'
          this.dialogWidth = '30%'
          // 重置 temp
          this.temp = {
            type: 'http',
            proxies: '',
            source: 'buy',
            tag: ''
          }
          this.innerDialogVisible = true
          break
        case 'edit':
          this.dialogTitle = '修改代理'
          this.dialogWidth = '30%'
          // 将 row 的信息赋给 temp，若需要回填 host/port/username/password，可自行拼接到 proxies 中
          this.temp = Object.assign({}, row)
          this.temp.proxies = `${row.host || ''}:${row.port || ''}:${row.username || ''}:${row.password || ''}`
          this.innerDialogVisible = true
          break
        case 'delete':
          this.dialogTitle = '删除代理'
          this.dialogWidth = '400px'
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'deleteBatch':
          // 批量删除
          if (!this.multipleSelection.length) return
          this.dialogTitle = `确认要删除选中的 ${this.multipleSelection.length} 条代理？`
          this.dialogWidth = '400px'
          this.temp = {} // 不需要具体信息，仅做提示
          this.innerDialogVisible = true
          break
      }
    },
    // 最终确认弹窗(增删改)
    confirm() {
      switch (this.action) {
        // eslint-disable-next-line no-case-declarations
        case 'create':
          // 将多行 proxies 拆解, 一行一条
          // 例如用户输入多行 ip:port:username:password
          const lines = this.temp.proxies.trim().split('\n')
          // 若要批量创建，可以遍历每行依次创建
          Promise.all(lines.map(line => {
            const [host, port, user, pass] = line.split(':')
            const payload = {
              host: host || '',
              port: port || '',
              username: user || '',
              password: pass || '',
              type: this.temp.type,
              source: this.temp.source,
              tag: this.temp.tag
            }
            return Post(payload)
          }))
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
            })
            .catch(error => {
              console.log(error)
            })
          break
        // eslint-disable-next-line no-case-declarations
        case 'edit':
          // 假设后端更新需要调用 Put(_id, payload)
          // 先将 proxies 里拆分出 host, port, user, pass
          const [hostE, portE, userE, passE] = this.temp.proxies.split(':')
          const payloadE = {
            host: hostE || '',
            port: portE || '',
            username: userE || '',
            password: passE || '',
            type: this.temp.type,
            source: this.temp.source,
            tag: this.temp.tag,
            isDead: this.temp.isDead
          }
          Put(this.temp.id, payloadE)
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
            })
            .catch(error => {
              console.log(error)
            })
          break
        case 'delete':
          Delete(this.temp.id)
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
            })
            .catch(error => {
              console.log(error)
            })
          break
        case 'deleteBatch':
          // 批量删除，多选
          Promise.all(
            this.multipleSelection.map(item => Delete(item.id))
          )
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
            })
            .catch(error => {
              console.log(error)
            })
          break
      }
    },
    // switch 切换可用状态
    handleUpdateStatus(row) {
      // 可在这里直接调用 Put() 更新 isDead 状态
      // 或者等下一次批量保存
      const payload = {
        host: row.host,
        port: row.port,
        username: row.username,
        password: row.password,
        type: row.type,
        source: row.source,
        tag: row.tag,
        isDead: row.isDead
      }
      Put(row.id, payload)
        .then(() => {
          // 更新成功
        })
        .catch(e => {
          console.log(e)
        })
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 若需要搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },

    // 若需要分页
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    }
  }
}
</script>

<style scoped>
.top {
  padding: 20px 0;
}
.add-btn {
  margin-left: 10px;
}
.mt-pagination {
  float: right;
  margin-top: 5px;
}
</style>
